/*
var options = {
    target: null,
    time: 0,
    autostart: true,
    callback: function(){},
    color: 'black',
    warning: {
        time: 5,
        message: '',
        color: 'red'
    },
    finish: {
        color: 'red',
        message: 'Time is elapsed.'
    }
}
*/

var countdown = function(options){
    var self = this;
    // ------------------------------------------------------- settings
    this.defaults = {
        time: 30,
        autostart: true,
        finish: {
            color: 'red',
            message: 'Time is elapsed.'
        }
    };
    
    this.settings = $.extend(true, {}, this.defaults, options);
    // ------------------------------------------------------- methods
    this.intervalId = null;
    this.timeRemaining = this.settings.time;
    
    this._getTime = function(){
        var min = Math.floor(this.timeRemaining / 60);
        var sec = this.timeRemaining - (min * 60);
        if (sec < 10) { sec = "0" + sec; }
        if (min < 10) { min = "0" + min; }
        return min + ":" + sec;
    }
    
    this._tic = function(){
        if(this.timeRemaining==null) return;
        var $result = $('<b>');
        
        if (this.timeRemaining > 0) {
            this.timeRemaining--;
            $result.text(this._getTime());
            
            if(this.settings.warning){
                if (this.timeRemaining == this.settings.warning.time) {
                    Notifier.warning(this.settings.warning.message);
                }
                if (this.timeRemaining < this.settings.warning.time && this.settings.warning.color) { 
                    $result.css('color',this.settings.warning.color);
                }
            }
            this.update($result);
        } else {
            this.stop();
            if(this.settings.finish.message) {
                $result.text(this.settings.finish.message);
                if(this.settings.finish.color){
                    $result.css('color',this.settings.finish.color);
                }
            }
            this.update($result);
            if(this.settings.callback) this.settings.callback();
        }
    }
    
    this.update = function($element){
        this.settings.target.find('*').remove();
        this.settings.target.append($element); 
    }
    
    this.start = function(){
        this.timeRemaining = this.settings.time;
        this.timeRemaining++;
        this.intervalId = setInterval(function(){
            self._tic();
        }, 1000)
    }
    
    this.stop = function(){
        clearInterval(this.intervalId);
        this.timeRemaining = null;
    }
    
    if(this.settings.autostart) this.start();
}